// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const orders = db.collection('orders')
  const openid = wxContext.OPENID

  try {
    const { orderId, totalAmount } = event
    
    if (!orderId) {
      return {
        success: false,
        message: '订单ID不能为空'
      }
    }

    // 查询订单信息
    const orderRes = await orders.doc(orderId).get()
    
    if (!orderRes.data) {
      return {
        success: false,
        message: '订单不存在'
      }
    }

    // 检查订单是否属于当前用户
    if (orderRes.data._openid !== openid) {
      return {
        success: false,
        message: '无权访问此订单'
      }
    }

    // 检查订单状态
    if (orderRes.data.payment_status === 'paid') {
      return {
        success: false,
        message: '订单已支付'
      }
    }

    // 生成微信支付参数
    const paymentParams = await generatePaymentParams({
      openid: openid,
      totalAmount: totalAmount,
      orderNo: orderRes.data.order_no,
      description: `订单${orderRes.data.order_no}`
    })

    // 更新订单状态为待支付
    await orders.doc(orderId).update({
      data: {
        payment_status: 'pending',
        updated_at: new Date()
      }
    })

    return {
      success: true,
      paymentParams: paymentParams,
      message: '支付参数生成成功'
    }
  } catch (error) {
    console.error('创建支付失败：', error)
    return {
      success: false,
      message: '创建支付失败'
    }
  }
}

// 生成微信支付参数
async function generatePaymentParams({ openid, totalAmount, orderNo, description }) {
  try {
    // 调用微信支付统一下单接口
    const result = await cloud.cloudPay.unifiedOrder({
      body: description,
      outTradeNo: orderNo,
      spbillCreateIp: '127.0.0.1',
      subMchId: '', // 子商户号，如果有的话
      totalFee: Math.round(totalAmount * 100), // 转换为分
      envId: cloud.DYNAMIC_CURRENT_ENV,
      functionName: 'pay_cb', // 支付回调云函数名
      nonceStr: generateNonceStr(),
      tradeType: 'JSAPI',
      openid: openid
    })

    if (result.returnCode === 'SUCCESS' && result.resultCode === 'SUCCESS') {
      // 生成小程序端支付参数
      const paymentParams = await cloud.cloudPay.getPayment({
        package: `prepay_id=${result.prepayId}`,
        nonceStr: generateNonceStr(),
        timeStamp: Math.floor(Date.now() / 1000).toString(),
        signType: 'MD5'
      })

      return {
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType,
        paySign: paymentParams.paySign
      }
    } else {
      throw new Error(result.returnMsg || '支付参数生成失败')
    }
  } catch (error) {
    console.error('生成支付参数失败：', error)
    throw error
  }
}

// 生成随机字符串
function generateNonceStr() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < 32; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
} 